#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <pthread.h>
#include "oled.h"

#define OLED_MESG_ADDRESS "../src/oled.txt"
#define BUFFER_SIZE 128
#define SHOW_MESG_TIME 5
int running = 1;
static FILE *oled_mesg_fd = NULL;
static pthread_t oled_mesg_tid;
void oled_CheckRecvMesg(char *msg);

typedef struct OLED_MESG
{
    char mesg[BUFFER_SIZE];
    int mesg_len;
} OLED_MESG;
OLED_MESG oled_mesg = {
    .mesg = {0},
    .mesg_len = 0,
};

enum
{
    OLED_MODE_SHOW_TIME = 0,
    OLED_MODE_SHOW_MESG,
    OLED_MODE_SHOW_MESG_END,
} oled_mode = OLED_MODE_SHOW_TIME;
// 主函数
int main()
{
    int wait_mesgEnd = 0;
    // 初始化OLED显示
    if (oled_init() == -1)
    {
        printf("OLED init failed\n");
        return EXIT_FAILURE;
    }

    oled_Clear();

    pthread_create(&oled_mesg_tid, NULL, (void *)oled_CheckRecvMesg, NULL);
    while (1)
    {
        switch (oled_mode)
        {
        case OLED_MODE_SHOW_TIME:
            oled_ShowTime();
            sleep(0.5);
            break;
        case OLED_MODE_SHOW_MESG:
            // oled_Clear();
            printf("oled message is:%s\n", oled_mesg.mesg);
            oled_ShowMesg(oled_mesg.mesg, oled_mesg.mesg_len);
            oled_mode = OLED_MODE_SHOW_MESG_END;
            wait_mesgEnd = 0;
            sleep(0.5);
            break;
        case OLED_MODE_SHOW_MESG_END:
            if (wait_mesgEnd++ <= 50)
            {
                // wait_mesgEnd++;
                usleep(100 * 1000);
                break;
            }
            oled_Clear();
            wait_mesgEnd = 0;
            oled_mode = OLED_MODE_SHOW_TIME;
            break;
        default:
            break;
        }
    }

    running = 0;
    close(i2c_fd);
    return EXIT_SUCCESS;
}

void oled_CheckRecvMesg(char *msg)
{
    static char ch;
    while (running)
    {
        oled_mesg_fd = fopen(OLED_MESG_ADDRESS, "r+");
        if (oled_mesg_fd == NULL)
        {
            printf("open %s failed\n", OLED_MESG_ADDRESS);
            oled_mesg.mesg_len = 0;
            sleep(1);
            continue;
        }
        fseek(oled_mesg_fd, 0, SEEK_SET);
        ch = fgetc(oled_mesg_fd);
        if (ch != '1')
        {
            fclose(oled_mesg_fd);
            continue;
        }
        fseek(oled_mesg_fd, 0, SEEK_SET);
        fputc('0', oled_mesg_fd);
        oled_mesg.mesg_len = fread(oled_mesg.mesg, 1, BUFFER_SIZE, oled_mesg_fd);
        printf("mesg_len = %d\n", oled_mesg.mesg_len);
        oled_mode = OLED_MODE_SHOW_MESG;
        fclose(oled_mesg_fd);
    }
}
